import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Select,
  DatePicker,
  Space,
  Button,
  Table,
  Progress,
  Tag,
  Tooltip
} from 'antd';
import {
  BarChartOutlined,
  PieChartOutlined,
  LineChartOutlined,
  ReloadOutlined,
  ExportOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  ToolOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';



const { RangePicker } = DatePicker;
const { Option } = Select;

// 统计数据接口
interface StatisticsData {
  totalAlarms: number;
  pendingAlarms: number;
  resolvedAlarms: number;
  processingAlarms: number;
  criticalAlarms: number;
  responseTime: number;
  resolutionRate: number;
  trendData: {
    date: string;
    total: number;
    resolved: number;
    pending: number;
  }[];
  buildingStats: {
    buildingName: string;
    buildingId: string;
    totalAlarms: number;
    pendingAlarms: number;
    resolutionRate: number;
    avgResponseTime: number;
  }[];
  typeStats: {
    type: string;
    typeName: string;
    count: number;
    percentage: number;
    color: string;
  }[];
  levelStats: {
    level: string;
    levelName: string;
    count: number;
    percentage: number;
    color: string;
  }[];
  deviceStats: {
    deviceName: string;
    deviceType: string;
    buildingName: string;
    alarmCount: number;
    lastAlarmTime: string;
    status: string;
  }[];
}

// 模拟统计数据
const mockStatisticsData: StatisticsData = {
  totalAlarms: 156,
  pendingAlarms: 23,
  resolvedAlarms: 118,
  processingAlarms: 15,
  criticalAlarms: 8,
  responseTime: 2.5,
  resolutionRate: 85.2,
  trendData: [
    { date: '2024-03-09', total: 12, resolved: 10, pending: 2 },
    { date: '2024-03-10', total: 15, resolved: 13, pending: 2 },
    { date: '2024-03-11', total: 8, resolved: 7, pending: 1 },
    { date: '2024-03-12', total: 18, resolved: 15, pending: 3 },
    { date: '2024-03-13', total: 22, resolved: 18, pending: 4 },
    { date: '2024-03-14', total: 16, resolved: 14, pending: 2 },
    { date: '2024-03-15', total: 19, resolved: 12, pending: 7 }
  ],
  buildingStats: [
    {
      buildingName: '华发新城A座',
      buildingId: '1',
      totalAlarms: 32,
      pendingAlarms: 5,
      resolutionRate: 84.4,
      avgResponseTime: 2.1
    },
    {
      buildingName: '商业综合体',
      buildingId: '2',
      totalAlarms: 28,
      pendingAlarms: 3,
      resolutionRate: 89.3,
      avgResponseTime: 1.8
    },
    {
      buildingName: '华发新城C座',
      buildingId: '3',
      totalAlarms: 35,
      pendingAlarms: 8,
      resolutionRate: 77.1,
      avgResponseTime: 3.2
    },
    {
      buildingName: '商业中心',
      buildingId: '4',
      totalAlarms: 24,
      pendingAlarms: 2,
      resolutionRate: 91.7,
      avgResponseTime: 1.5
    },
    {
      buildingName: '华发二期办公楼D座',
      buildingId: 'P2-O4',
      totalAlarms: 18,
      pendingAlarms: 3,
      resolutionRate: 83.3,
      avgResponseTime: 2.4
    },
    {
      buildingName: '华发二期住宅楼5号楼',
      buildingId: 'P2-R5',
      totalAlarms: 19,
      pendingAlarms: 2,
      resolutionRate: 89.5,
      avgResponseTime: 2.0
    }
  ],
  typeStats: [
    { type: 'elevator', typeName: '电梯', count: 45, percentage: 28.8, color: '#1890ff' },
    { type: 'hvac', typeName: '空调', count: 32, percentage: 20.5, color: '#52c41a' },
    { type: 'security', typeName: '安防', count: 28, percentage: 17.9, color: '#722ed1' },
    { type: 'fire', typeName: '消防', count: 22, percentage: 14.1, color: '#f5222d' },
    { type: 'access', typeName: '门禁', count: 18, percentage: 11.5, color: '#fa8c16' },
    { type: 'lighting', typeName: '照明', count: 11, percentage: 7.1, color: '#fadb14' }
  ],
  levelStats: [
    { level: 'critical', levelName: '紧急', count: 8, percentage: 5.1, color: '#f5222d' },
    { level: 'high', levelName: '重要', count: 35, percentage: 22.4, color: '#fa8c16' },
    { level: 'medium', levelName: '一般', count: 78, percentage: 50.0, color: '#1890ff' },
    { level: 'low', levelName: '轻微', count: 35, percentage: 22.4, color: '#52c41a' }
  ],
  deviceStats: [
    {
      deviceName: '高速电梯C2',
      deviceType: '电梯',
      buildingName: '华发新城C座',
      alarmCount: 8,
      lastAlarmTime: '2024-03-15 14:30:25',
      status: 'critical'
    },
    {
      deviceName: '中央空调',
      deviceType: '空调',
      buildingName: '商业中心',
      alarmCount: 6,
      lastAlarmTime: '2024-03-15 09:45:12',
      status: 'high'
    },
    {
      deviceName: '安防监控',
      deviceType: '安防',
      buildingName: '高层公寓',
      alarmCount: 5,
      lastAlarmTime: '2024-03-15 07:15:30',
      status: 'medium'
    },
    {
      deviceName: '高速电梯E2',
      deviceType: '电梯',
      buildingName: '华发二期办公楼D座',
      alarmCount: 4,
      lastAlarmTime: '2024-03-15 10:15:30',
      status: 'medium'
    },
    {
      deviceName: '门禁系统',
      deviceType: '门禁',
      buildingName: '华发新城A座',
      alarmCount: 4,
      lastAlarmTime: '2024-03-15 06:00:45',
      status: 'low'
    }
  ]
};

const AlarmStatistics: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [statisticsData, setStatisticsData] = useState<StatisticsData>(mockStatisticsData);
  const [dateRange, setDateRange] = useState<any>(null);
  const [selectedBuilding, setSelectedBuilding] = useState<string>('');

  // 刷新数据
  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  };

  // 导出数据
  const handleExport = () => {
    console.log('导出统计数据');
  };

  // 趋势图表配置
  const trendChartData = {
    labels: statisticsData.trendData.map(item => dayjs(item.date).format('MM-DD')),
    datasets: [
      {
        label: '总报警数',
        data: statisticsData.trendData.map(item => item.total),
        borderColor: '#1890ff',
        backgroundColor: 'rgba(24, 144, 255, 0.1)',
        fill: true,
        tension: 0.4
      },
      {
        label: '已解决',
        data: statisticsData.trendData.map(item => item.resolved),
        borderColor: '#52c41a',
        backgroundColor: 'rgba(82, 196, 26, 0.1)',
        fill: true,
        tension: 0.4
      },
      {
        label: '待处理',
        data: statisticsData.trendData.map(item => item.pending),
        borderColor: '#f5222d',
        backgroundColor: 'rgba(245, 34, 45, 0.1)',
        fill: true,
        tension: 0.4
      }
    ]
  };

  const trendChartOptions = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top' as const,
      },
      title: {
        display: true,
        text: '报警趋势分析'
      }
    },
    scales: {
      y: {
        beginAtZero: true
      }
    }
  };

  // 类型分布饼图配置
  const typeChartData = {
    labels: statisticsData.typeStats.map(item => item.typeName),
    datasets: [
      {
        data: statisticsData.typeStats.map(item => item.count),
        backgroundColor: statisticsData.typeStats.map(item => item.color),
        borderWidth: 2,
        borderColor: '#fff'
      }
    ]
  };

  const typeChartOptions = {
    responsive: true,
    plugins: {
      legend: {
        position: 'right' as const,
      },
      title: {
        display: true,
        text: '报警类型分布'
      }
    }
  };

  // 等级分布柱状图配置
  const levelChartData = {
    labels: statisticsData.levelStats.map(item => item.levelName),
    datasets: [
      {
        label: '报警数量',
        data: statisticsData.levelStats.map(item => item.count),
        backgroundColor: statisticsData.levelStats.map(item => item.color),
        borderWidth: 1
      }
    ]
  };

  const levelChartOptions = {
    responsive: true,
    plugins: {
      legend: {
        display: false
      },
      title: {
        display: true,
        text: '报警等级分布'
      }
    },
    scales: {
      y: {
        beginAtZero: true
      }
    }
  };

  // 楼宇统计表格列配置
  const buildingColumns: ColumnsType<any> = [
    {
      title: '楼宇名称',
      dataIndex: 'buildingName',
      key: 'buildingName',
      width: 200
    },
    {
      title: '总报警数',
      dataIndex: 'totalAlarms',
      key: 'totalAlarms',
      width: 100,
      sorter: (a, b) => a.totalAlarms - b.totalAlarms
    },
    {
      title: '待处理',
      dataIndex: 'pendingAlarms',
      key: 'pendingAlarms',
      width: 100,
      render: (count) => (
        <Tag color={count > 5 ? 'red' : count > 2 ? 'orange' : 'green'}>
          {count}
        </Tag>
      )
    },
    {
      title: '解决率',
      dataIndex: 'resolutionRate',
      key: 'resolutionRate',
      width: 120,
      render: (rate) => (
        <div>
          <Progress 
            percent={rate} 
            size="small" 
            status={rate >= 90 ? 'success' : rate >= 80 ? 'normal' : 'exception'}
          />
          <span style={{ marginLeft: 8 }}>{rate}%</span>
        </div>
      ),
      sorter: (a, b) => a.resolutionRate - b.resolutionRate
    },
    {
      title: '平均响应时间',
      dataIndex: 'avgResponseTime',
      key: 'avgResponseTime',
      width: 120,
      render: (time) => (
        <span>
          {time < 2 ? (
            <ArrowDownOutlined style={{ color: '#52c41a', marginRight: 4 }} />
          ) : time > 3 ? (
            <ArrowUpOutlined style={{ color: '#f5222d', marginRight: 4 }} />
          ) : (
            <BarChartOutlined style={{ color: '#1890ff', marginRight: 4 }} />
          )}
          {time}小时
        </span>
      ),
      sorter: (a, b) => a.avgResponseTime - b.avgResponseTime
    }
  ];

  // 设备统计表格列配置
  const deviceColumns: ColumnsType<any> = [
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
      width: 150
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      width: 100,
      render: (type) => <Tag color="blue">{type}</Tag>
    },
    {
      title: '所属楼宇',
      dataIndex: 'buildingName',
      key: 'buildingName',
      width: 150
    },
    {
      title: '报警次数',
      dataIndex: 'alarmCount',
      key: 'alarmCount',
      width: 100,
      sorter: (a, b) => a.alarmCount - b.alarmCount,
      render: (count) => (
        <Tag color={count >= 8 ? 'red' : count >= 5 ? 'orange' : 'green'}>
          {count}
        </Tag>
      )
    },
    {
      title: '最近报警时间',
      dataIndex: 'lastAlarmTime',
      key: 'lastAlarmTime',
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = {
          critical: { color: 'red', text: '紧急', icon: <ExclamationCircleOutlined /> },
          high: { color: 'orange', text: '重要', icon: <WarningOutlined /> },
          medium: { color: 'blue', text: '一般', icon: <ToolOutlined /> },
          low: { color: 'green', text: '正常', icon: <CheckCircleOutlined /> }
        };
        const { color, text, icon } = config[status as keyof typeof config] || config.low;
        return <Tag color={color} icon={icon}>{text}</Tag>;
      }
    }
  ];

  return (
    <div className="alarm-statistics-container">
      {/* 筛选区域 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={8}>
            <Space>
              <span>时间范围：</span>
              <RangePicker
                value={dateRange}
                onChange={setDateRange}
                placeholder={['开始时间', '结束时间']}
              />
            </Space>
          </Col>
          <Col span={6}>
            <Space>
              <span>楼宇筛选：</span>
              <Select
                placeholder="选择楼宇"
                value={selectedBuilding}
                onChange={setSelectedBuilding}
                allowClear
                style={{ width: 200 }}
              >
                {statisticsData.buildingStats.map(building => (
                  <Option key={building.buildingId} value={building.buildingId}>
                    {building.buildingName}
                  </Option>
                ))}
              </Select>
            </Space>
          </Col>
          <Col span={10} style={{ textAlign: 'right' }}>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                刷新
              </Button>
              <Button type="primary" icon={<ExportOutlined />} onClick={handleExport}>
                导出报告
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 核心指标卡片 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总报警数"
              value={statisticsData.totalAlarms}
              valueStyle={{ color: '#1890ff' }}
              prefix={<BarChartOutlined />}
              suffix="条"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待处理报警"
              value={statisticsData.pendingAlarms}
              valueStyle={{ color: '#f5222d' }}
              prefix={<ExclamationCircleOutlined />}
              suffix="条"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均响应时间"
              value={statisticsData.responseTime}
              precision={1}
              valueStyle={{ color: '#fa8c16' }}
              prefix={<ToolOutlined />}
              suffix="小时"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="解决率"
              value={statisticsData.resolutionRate}
              precision={1}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
              suffix="%"
            />
          </Card>
        </Col>
      </Row>

      {/* 趋势数据展示 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Card title="报警趋势分析" extra={<LineChartOutlined />}>
            <Row gutter={16}>
              {statisticsData.trendData.map((item, index) => (
                <Col span={3} key={index}>
                  <Card size="small">
                    <Statistic
                      title={dayjs(item.date).format('MM-DD')}
                      value={item.total}
                      valueStyle={{ fontSize: 16 }}
                      suffix={
                        <div style={{ fontSize: 12, color: '#666' }}>
                          <div>解决: {item.resolved}</div>
                          <div>待处理: {item.pending}</div>
                        </div>
                      }
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={12}>
          <Card title="报警类型分布" extra={<PieChartOutlined />}>
            <Row gutter={[16, 16]}>
              {statisticsData.typeStats.map((item, index) => (
                <Col span={12} key={index}>
                  <Card size="small" style={{ borderLeft: `4px solid ${item.color}` }}>
                    <Statistic
                      title={item.typeName}
                      value={item.count}
                      suffix={`(${item.percentage}%)`}
                      valueStyle={{ color: item.color }}
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="报警等级分布" extra={<BarChartOutlined />}>
            <Row gutter={[16, 16]}>
              {statisticsData.levelStats.map((item, index) => (
                <Col span={12} key={index}>
                  <Card size="small" style={{ borderLeft: `4px solid ${item.color}` }}>
                    <Statistic
                      title={item.levelName}
                      value={item.count}
                      suffix={`(${item.percentage}%)`}
                      valueStyle={{ color: item.color }}
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
      </Row>

      {/* 楼宇统计表格 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Card title="楼宇报警统计" extra={<Tooltip title="各楼宇报警处理情况统计"><BarChartOutlined /></Tooltip>}>
            <Table
              columns={buildingColumns}
              dataSource={statisticsData.buildingStats}
              rowKey="buildingId"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>

      {/* 设备统计表格 */}
      <Row gutter={16}>
        <Col span={24}>
          <Card title="高频报警设备统计" extra={<Tooltip title="报警频次较高的设备列表"><WarningOutlined /></Tooltip>}>
            <Table
              columns={deviceColumns}
              dataSource={statisticsData.deviceStats}
              rowKey="deviceName"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              }}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default AlarmStatistics;